package com.haiyou.common.spring.log.warning.config;

import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.haiyou.common.spring.log.warning.appender.ExceptionLogAppender;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.filter.ThresholdFilter;

/**
 * 
 * @Description: logback 配置
 * @author xingyuan
 * @date 2023年3月30日 上午11:48:21
 */
@Configuration
@ConditionalOnClass(LoggerContext.class)
public class LogbackWarningConfig {

	@Bean
	@ConditionalOnMissingBean
	public LoggerContext loggerContext() {
		return (LoggerContext) LoggerFactory.getILoggerFactory();
	}

	/**
	 * 注册一个异常处理 Appender
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean
	public ExceptionLogAppender consoleAppender() {
		ExceptionLogAppender appender = new ExceptionLogAppender();
		appender.setContext(loggerContext());
		appender.setName("exceptionLogAppender");
		
		//编码器
		PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext());
        encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSSS} [%thread] %-5level %logger{36}-[Line:%L]>%m%n"); 
		encoder.start();
		
		//过滤器
		ThresholdFilter filter = new ThresholdFilter();
		filter.setLevel("ERROR");
		filter.setContext(loggerContext());
		filter.start();
		
		appender.addFilter(filter);
		appender.setEncoder(encoder);
		appender.start();
		
		//添加进入
		Logger rootLogger = loggerContext().getLogger(Logger.ROOT_LOGGER_NAME);
		rootLogger.addAppender(appender);
		
		return appender;
	}

	
}
